package com.ruoyi.web.plan.controller;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.web.plan.domain.*;
import com.ruoyi.web.plan.service.IProjectService;
import com.ruoyi.web.plan.service.ITaskInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.web.plan.service.IDutyService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.utils.poi.ExcelUtil;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 日报任务Controller
 *
 * @author ruoyi
 * @date 2025-01-30
 */
@RestController
@RequestMapping("/plan/duty")
public class DutyController extends BaseController {
    @Autowired
    private IDutyService dutyService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ITaskInfoService taskInfoService;

    /**
     * 查询日报任务列表
     */
    @SaCheckPermission("plan:duty:list")
    @GetMapping("/list")
    public TableDataInfo list(Duty duty) {
        startPage();
        List<Duty> list = dutyService.selectDutyList(duty);
        return getDataTable(list);
    }

    /**
     * 导出日报任务列表
     */
    @SaCheckPermission("plan:duty:export")
    @Log(title = "日报任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Duty duty) {
        List<Duty> list = dutyService.selectDutyList(duty);
        ExcelUtil<Duty> util = new ExcelUtil<Duty>(Duty.class);
        util.exportExcel(response, list, "日报任务数据");
    }

    /**
     * 获取日报任务详细信息
     */
    @SaCheckPermission("plan:duty:query")
    @GetMapping(value = "/{dutyId}")
    public AjaxResult getInfo(@PathVariable("dutyId") Long dutyId) {
        return success(dutyService.selectDutyByDutyId(dutyId));
    }

    /**
     * 新增日报任务
     */
    @SaCheckPermission("plan:duty:add")
    @Log(title = "日报任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Duty duty) {
        return toAjax(dutyService.insertDuty(duty));
    }

    /**
     * 修改日报任务
     */
    @SaCheckPermission("plan:duty:edit")
    @Log(title = "日报任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Duty duty) {
        return toAjax(dutyService.updateDuty(duty));
    }

    /**
     * 删除日报任务
     */
    @SaCheckPermission("plan:duty:remove")
    @Log(title = "日报任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dutyIds}")
    public AjaxResult remove(@PathVariable Long[] dutyIds) {
        return toAjax(dutyService.deleteDutyByDutyIds(dutyIds));
    }


    /**
     * 获取日报任务详细信息
     */
    @SaCheckPermission("plan:duty:query")
    @GetMapping(value = "/Statistics/{mouthTime}")
    public AjaxResult getStatistics(@PathVariable String mouthTime) {
        List<Project> projectList = projectService.selectProjectList(null);
        List<TaskInfo> taskList = taskInfoService.selectTaskInfoList(null);
        List<Duty> dutyList = dutyService.selectDutyList(null);
        logger.debug("============" + taskList);
        List<DutyStatistics> dutyStatisticsList = new ArrayList<>();
        for (Project proItem : projectList) {
            DutyStatistics item = new DutyStatistics();
            item.setProjectId(proItem.getProjectId());
            item.setProjectName(proItem.getProjectName());
            //
            int taskFinishCount = 0;
            int totalCount = 0;
            int mouthFinishTask = 0;
            for (TaskInfo taskItem : taskList) {
                if (Objects.equals(proItem.getProjectId(), taskItem.getProjectId())) {
                    totalCount = totalCount + 1;
                    //完成状态
                    if (taskItem.getRunState().equalsIgnoreCase("3")) {
                        taskFinishCount = taskFinishCount + 1;
                        //这个月完成的task
                        if (isDateInMonth(mouthTime, taskItem.getEndTime())) {
                            mouthFinishTask = mouthFinishTask + 1;
                        }
                    }
                }
            }
//            logger.debug("============totalCount  " + totalCount);
//            logger.debug("============taskFinishCount  " + taskFinishCount);
            item.setTotalTask(totalCount);
            item.setFinishTask(taskFinishCount);

            //每个项目在这个月花的时间
            BigDecimal useTime = BigDecimal.valueOf(0);
            for (Duty duty : dutyList) {
                logger.debug("============  duty=" + duty.getUseTime());
                if (Objects.equals(proItem.getProjectId(), duty.getProjectId()) && isDateInMonth(mouthTime, duty.getDutyDate())) {
                    if (duty.getUseTime() != null) {
                        logger.debug("============getUseTime  " + duty.getUseTime());
                        useTime = useTime.add(duty.getUseTime());
                    }
                }
            }
            logger.debug("============  useTime=" + useTime);
            item.setUseTime(useTime);
            dutyStatisticsList.add(item);
        }
        return success(dutyStatisticsList);
    }

    //

    /**
     * 判断 Date 是否在指定月份内
     *
     * @param date        需要判断的 Date 对象
     * @param monthString 月份字符串，格式为 "yyyy-MM"
     * @return 如果 Date 在指定月份内，返回 true；否则返回 false
     */
    public static boolean isDateInMonth(String monthString, Date date) {
        // 将月份字符串解析为 YearMonth 对象
        YearMonth targetMonth = YearMonth.parse(monthString);

        // 将 Date 转换为 LocalDate
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 比较年份和月份
        return YearMonth.from(localDate).equals(targetMonth);
    }


}
